package main

import (
	"bufio"
	"context"
	"gitee.com/leonscript/portal/filex"
	"github.com/zeromicro/go-zero/core/logc"
	"log"
	"net"
	"os"
	"strings"
	"time"
)

func init() {
	// 初始化日志控件
	initLogc()
}

func main() {
	initUDSServer()
}

func initUDSServer() {
	// 定义UDS文件路径
	socketPath := "./logs.sock"

	// 启动前确保UDS文件不存在
	if err := os.Remove(socketPath); err != nil && !os.IsNotExist(err) {
		log.Fatal("Failed to remove existing socket:", err)
	}

	// 创建Unix域套接字监听器
	listener, err := net.ListenUnix("unix", &net.UnixAddr{Name: socketPath, Net: "unix"})
	if err != nil {
		log.Fatal("Failed to listen on Unix socket:", err)
	}
	defer listener.Close()

	logc.Info(context.TODO(), "UDS server is running on ", socketPath)

	// 启动日志写入器
	fwriter, err := filex.NewFileWriter(600)
	if err != nil {
		panic(err)
	}
	go fwriter.StartListening()

	// 处理客户端连接
	for {
		// 获取链接
		conn, err := listener.AcceptUnix()
		if err != nil {
			logc.Error(context.TODO(), "Failed to accept connection:", err)
			continue
		}
		// 处理链接信息
		go handleConnection(conn, fwriter)
	}
}

func handleConnection(conn *net.UnixConn, fwriter *filex.FileWriter) {
	defer conn.Close()

	// 使用bufio.Reader读取数据
	reader := bufio.NewReader(conn)
	for {
		// 处理沾包
		message, err := reader.ReadString('$')
		if err != nil {
			logc.Error(context.TODO(), "Error reading from connection:", err.Error())
			return
		}

		// 消息写入日志
		fwriter.Write(strings.Replace(message, "$", "", -1))
	}
}

// initLogc 初始化日志控件
func initLogc() {
	// 初始化日志配置
	var logConf logc.LogConf

	// 日志文件滚动配置
	logConf.Mode = "file"
	logConf.Path = "./logs"
	logConf.KeepDays = 1

	// 日志时间格式配置
	logConf.TimeFormat = time.DateTime

	// 配置生效
	logc.MustSetup(logConf)
}
